package com.w3c.pragmatic.config;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 线程池配置
 *
 * @author wangdong
 * @since 2025/2/24 11:10
 */
@Slf4j
@Data
@Configuration
public class ThreadPoolConfig {

  @Value("${core.pool.size:1}")
  @ApiModelProperty(value = "常驻线程数")
  private int corePoolSize;

  @Value("${maximum.pool.size:3}")
  @ApiModelProperty(value = "最大线程数")
  private int maximumPoolSize;

  @Value("${keep.alive.time:10}")
  @ApiModelProperty(value = "空闲等待时间")
  private long keepAliveTime;

  @Value("${thread.work.queue:10}")
  @ApiModelProperty(value = "阻塞队列大小")
  private int workQueueSize;

  // 创建线程池
  @Bean("commonThreadExecutor")
  public ThreadPoolExecutor createCustomerThreadPool() {
    // 获取cpu核数
    // 至于io密集型还是cpu密集型在于corePoolSize的计算和配置
    // corePoolSize = Runtime.getRuntime().availableProcessors();
    // 自定义拒绝策略
    ThreadPoolExecutor threadPoolExecutor =
        new ThreadPoolExecutor(
            corePoolSize,
            maximumPoolSize,
            keepAliveTime,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(workQueueSize),
            Executors.defaultThreadFactory(),
            // 自定义拒绝策略
            (r, executor) -> {
              final Thread t = new Thread(r, "Temporary task executor");
              t.start();
            });
    log.info("ThreadPoolConfig#ThreadPoolExecutor线程池初始化成功！");
    // 返回线程池
    return threadPoolExecutor;
  }
}
